package com.ghsc.ghxc.jsb.ui.login

import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.Log
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.config.AppConfig
import com.cn.appcore.ext.gone
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.visible
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.ActivityLoginBinding
import com.ghsc.ghxc.jsb.ext.isVisible
import com.ghsc.ghxc.jsb.ui.main.MainActivity

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.login
 * 类名：LoginActivity
 * 创建时间：2024/4/22 11:09
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class LoginActivity : BaseVMActivity<LoginViewModel, ActivityLoginBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_login
    }

    override fun attachVMClass(): Class<LoginViewModel>? {
        return LoginViewModel::class.java
    }


    var myCountDownTimer: MyCountDownTimer? = null

    private var isPwdVisible = false

    var type=1 //登录注册


    override fun onResume() {
        super.onResume()
        mViewModel.onSysConfigMethod("")


    }

    override fun initView() {
        showType()
    }

    //登录/注册
    private fun showType(){
        if (type==1){
            binding.btnLogin.text="登录"
            binding.btnToType.text="没有账号？去注册"
            binding.rllVerificationCode.gone()
            binding.rllInvite.gone()
        }else{
            binding.btnLogin.text="注册"
            binding.btnToType.text="已有账号？去登录"
            binding.rllVerificationCode.visible()
            binding.rllInvite.visible()
        }
    }



    override fun initClickListener() {
        super.initClickListener()

        //切换登录或者注册
        binding.btnToType.setSingleClickListener {
            type=if(type==1)2 else 1
            showType()
        }
        //协议
        binding.tvBtnAge.setSingleClickListener {
            var bundle = Bundle()
            bundle.putInt("sign",1)
            startActivity(AgreementActivity().javaClass,bundle)
        }
        //忘记密码
        binding.btnForgetPwd.setSingleClickListener {
            var bundle = Bundle()
            bundle.putInt("sign",1)
            startActivity(RetrievePwdActivity().javaClass,bundle)

        }
        //隐藏显示密码
        binding.ivLoginPwdEye.setSingleClickListener(200) {
            binding.ivLoginPwdEye.setImageResource(if (isPwdVisible) R.drawable.icon_pwd_gone else R.drawable.icon_pwd_show)
            binding.etLoginPwd.transformationMethod = if (isPwdVisible) {
                PasswordTransformationMethod.getInstance()
            } else {
                HideReturnsTransformationMethod.getInstance()
            }
            val pwdStr = binding.etLoginPwd.text ?: ""
            binding.etLoginPwd.setSelection(pwdStr.length)
            isPwdVisible = !isPwdVisible
        }
        //验证码
        binding.tvBtnCode.setSingleClickListener {
            if (TextUtils.isEmpty(binding.etPhone.text)){
                showToast("请输入手机号")
                return@setSingleClickListener
            }
            val map: HashMap<String, Any> = HashMap()
            map["mobile"] = binding.etPhone.text.toString().trim()
            map["type"]=1
            GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onPhoneCodeMethod(it1) }
        }
        //登录  注册
        binding.btnLogin.setSingleClickListener {

            val isChecked = binding.cbUserAgreement.isChecked
            if (!isChecked) {
                showToast("请阅读并同意《用户服务协议及隐私政策》")
                binding.cbUserAgreement.isChecked=true
                return@setSingleClickListener
            }
            val  phoneStr = binding.etPhone.text.toString().trim()
            val loginPwd = binding.etLoginPwd.text.toString().trim()
            if (TextUtils.isEmpty(phoneStr)){
                showToast("请输入手机号")
                return@setSingleClickListener
            }
            if (phoneStr.length != 11) {
                showToast("手机格式错误")
                return@setSingleClickListener
            }
            if (TextUtils.isEmpty(loginPwd)){
                showToast("请输入密码")
                return@setSingleClickListener
            }
            if (loginPwd.length < 6) {
                showToast("密码错误，不得少于6位")
                return@setSingleClickListener
            }
            if (type == 2){
                if (TextUtils.isEmpty(binding.etInvitationCode.text) && binding.rllInvite.isVisible){
                    showToast("请输入邀请码")
                    return@setSingleClickListener
                }
                if (TextUtils.isEmpty(binding.etCode.text)){
                    showToast("请输入验证码")
                    return@setSingleClickListener
                }
//                if (TextUtils.isEmpty(binding.etPayPwd.text)){
//                    showToast("请输入支付密码")
//                    return@setSingleClickListener
//                }
                // 注册
                val map: HashMap<String, Any> = HashMap()
                map["mobile"] = binding.etPhone.text.toString().trim()
                map["password"] = binding.etLoginPwd.text.toString().trim()
                map["paypassword"] = ""
                map["smscode"] = binding.etCode.text.toString().trim()
                map["yqcode"] = binding.etInvitationCode.text.toString().trim()
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onUserRegisterMethod(it1) }
            }else {
                //登录
                val map: HashMap<String, Any> = HashMap()
                map["mobile"] = phoneStr
                map["password"] = loginPwd
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onLoginMethod( it1) }
            }
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@LoginActivity) {
                dismissLoading()
                showToast(it)
            }
            againLoginMsg.observe(this@LoginActivity) {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)

            }
            onSysConfigData.observe(this@LoginActivity) {
                //保存配置
                UserManager.saveConfig(it)
            }
            onPhoneCodeData.observe(this@LoginActivity) {
                if (myCountDownTimer==null)
                    myCountDownTimer = MyCountDownTimer(60000, 1000)
                showToast("验证码发送成功")
                myCountDownTimer?.start()
            }
            loginData.observe(this@LoginActivity) {
                dismissLoading()
                var userId: String by Preference(HttpConstant.USER_ID, "")
                var userRid: String by Preference(HttpConstant.USER_RID, "")
                userId = it.data.data.uid
                userRid=it.data.data.rid
                if (!TextUtils.isEmpty(userId)) {
                    UserManager.setUserId(it.data.data.uid)
                    UserManager.setUserName(it.data.data.nickname)
                    UserManager.setUserHead(it.data.data.headimg)
                    showToast("登录成功")
                    var isLogin: String by Preference(HttpConstant.APP_IS_LOGIN, "")
                    isLogin = "1"
                    startActivity(MainActivity().javaClass)
                    //除了登录activity不关闭。其余的都关闭。
                    AppConfig.getActivityManager()
                        ?.popAllActivityExceptOne(MainActivity::class.java)
                }
            }
            onUserRegisterData.observe(this@LoginActivity) {
                dismissLoading()
                showToast("注册成功")
                var userId: String by Preference(HttpConstant.USER_ID, "")
                var userRid: String by Preference(HttpConstant.USER_RID, "")
                userId = it.data.data.uid
                userRid=it.data.data.rid
                if (!TextUtils.isEmpty(userId)) {
                    UserManager.setUserId(it.data.data.uid)
                    UserManager.setUserName(it.data.data.nickname)
                    UserManager.setUserHead(it.data.data.headimg)
                    showToast("登录成功")
                    var isLogin: String by Preference(HttpConstant.APP_IS_LOGIN, "")
                    isLogin = "1"
                    startActivity(MainActivity().javaClass)
                    //除了登录activity不关闭。其余的都关闭。
                    AppConfig.getActivityManager()
                        ?.popAllActivityExceptOne(MainActivity::class.java)
                }

            }
        }
    }


    /**
     * 倒计时函数
     */
    inner class MyCountDownTimer(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {
        //计时过程
        override fun onTick(l: Long) {
            //防止计时过程中重复点击
            binding.tvBtnCode.isClickable = false
            binding.tvBtnCode.text = (l / 1000).toString() + "s"
        }

        //计时完毕的方法
        override fun onFinish() {
            //设置可点击
            binding.tvBtnCode.text = resources.getString(R.string.time_again_str)
            binding.tvBtnCode.isClickable = true
        }
    }


}